/**
 * Copyright 2013 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2013-6-19 下午2:43:31
 */
package com.absir.bean.inject;

import java.lang.reflect.Field;

import com.absir.bean.basis.BeanFactory;
import com.absir.bean.inject.value.InjectType;
import com.absir.core.kernel.KernelClass;
import com.absir.core.kernel.KernelLang.CauseRuntimeException;
import com.absir.core.kernel.KernelString;

/**
 * @author absir
 * 
 */
public class InjectField extends InjectInvoker {

	/** field */
	Field field;

	/** value */
	String value;

	/**
	 * @param field
	 * @param value
	 * @param injectType
	 */
	public InjectField(Field field, String value, InjectType injectType) {
		super(injectType);
		this.field = field;
		this.value = KernelString.isEmpty(value) ? null : value;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.absir.bean.inject.InjectInvoker#support(java.lang.Class)
	 */
	@Override
	public boolean support(Class<?> beanType) {
		// TODO Auto-generated method stub
		return beanType.isAssignableFrom(KernelClass.componentClass(field.getGenericType()));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.absir.bean.inject.InjectInvoker#invoke(com.absir.bean.basis.BeanFactory
	 * , java.lang.Object)
	 */
	@Override
	public void invoke(BeanFactory beanFactory, Object beanObject) {
		// TODO Auto-generated method stub
		Object object = beanFactory.getBeanObject(value == null ? field.getName() : value, field.getGenericType(),
				value != null);
		if (injectType == InjectType.Required && object == null) {
			throw new RuntimeException("can not inject " + field.getDeclaringClass() + ".field " + field);
		}

		try {
			field.set(beanObject, object);

		} catch (Exception e) {
			throw new CauseRuntimeException(e);
		}
	}
}
